package com.starblink.imgsearch.barcoderesult.ui

import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.BindingAdapter
import com.starblink.android.basic.brv.utils.defaultDividerStagger
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.brv.utils.staggered
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.setEmptyViewForWishTemplate
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.route.RoutePage
import com.starblink.imgsearch.R
import com.starblink.imgsearch.barcoderesult.data.RvNoProductEntry
import com.starblink.imgsearch.barcoderesult.data.RvProductEntry
import com.starblink.imgsearch.barcoderesult.data.RvTitleEntry
import com.starblink.imgsearch.databinding.ActivityBarcodeResultBinding
import com.starblink.imgsearch.databinding.CellBarcodeResultNoProductsBinding
import com.starblink.imgsearch.databinding.CellBarcodeResultStandardProductBinding
import com.starblink.imgsearch.databinding.CellBarcodeResultTitleBinding
import com.starblink.library.widget.databinding.CellSimpleProductCardBinding
import com.starblink.library.widget.product.ProductCardScene
import com.starblink.rocketreserver.FetchProductByGtin14Query
import com.starblink.rocketreserver.fragment.ProductF

/**
 * 条形码搜索结果页
 */
@Route(path = RoutePage.ImageSearch.PAGE_BARCODE_RESULT)
class BarcodeResultActivity : BaseTVMActivity<ActivityBarcodeResultBinding, BarcodeResultVM>() {
    private companion object {
        const val TAG = "BarcodeResult"
    }

    /**商品条形码*/
    @Autowired(name = RoutePage.ImageSearch.ARGS_PRODUCT_BARCODE)
    @JvmField
    var productBarcode: String = ""

    override fun initViewBinding(): ActivityBarcodeResultBinding =
        ActivityBarcodeResultBinding.inflate(layoutInflater)

    override fun initData() {
        super.initData()
        viewModel.barcode = productBarcode
    }

    override fun initView() {
        super.initView()
        viewBinding.vBackIcon.click {
            finish()
        }

        //初始化列表相关
        viewBinding.rv.itemAnimator = FadeInAnimator()
        viewBinding.rv.staggered(2).defaultDividerStagger().setup {
            // 四种列表项类型
            addType<RvProductEntry, CellSimpleProductCardBinding>(it)
            addType<FetchProductByGtin14Query.StdProduct, CellBarcodeResultStandardProductBinding>(
                it
            )
            addType<RvNoProductEntry, CellBarcodeResultNoProductsBinding>(it)
            addType<RvTitleEntry, CellBarcodeResultTitleBinding>(it)

            onBind {
                when (itemViewType) {
                    com.starblink.library.widget.R.layout.cell_simple_product_card -> {
                        // 列表项:商品卡片
                        val vb = getBinding<CellSimpleProductCardBinding>()
                        val entry = getModel<RvProductEntry>()
                        entry.position = layoutPosition

                        vb.card.scene =
                            if (entry.isStandardProduct) ProductCardScene.BARCODE_SEARCH else ProductCardScene.BARCODE_SEARCH_RECOMMEND
                        vb.card.bindProduct(
                            refreshLayout = viewBinding.page,
                            recyclerView = viewBinding.rv,
                            productWrap = entry,
                            position = layoutPosition,
                            guideType = TAG
                        )
                    }

                    R.layout.cell_barcode_result_standard_product -> {
                        // 列表项:标品商品
                        bindStandardProduct()
                    }

                    R.layout.cell_barcode_result_title -> {
                        // 列表项:标题
                        val viewBinding = getBinding<CellBarcodeResultTitleBinding>()
                        val entry = getModel<RvTitleEntry>()
                        // 占满一行
                        viewBinding.root.layoutParams =
                            (viewBinding.root.layoutParams as StaggeredGridLayoutManager.LayoutParams).apply {
                                isFullSpan = true
                            }
                        viewBinding.vTitle.text = entry.title
                    }

                    R.layout.cell_barcode_result_no_products -> {
                        // 列表项：无搜索结果空视图
                        val viewBinding = getBinding<CellBarcodeResultNoProductsBinding>()
                        viewBinding.root.layoutParams =
                            (viewBinding.root.layoutParams as StaggeredGridLayoutManager.LayoutParams).apply {
                                isFullSpan = true
                            }
                    }
                }
            }

            viewBinding.page.onEmpty {
                post {
                    setEmptyViewForWishTemplate(
                        title = "Oops!",
                        subTitle = "Sorry, no products have been found.",
                        marginTop = 37.dp,
                    )
                }
            }

            viewBinding.page.onRefresh {
                viewModel.loadSearchResult()
            }
            viewBinding.page.onLoadMore {
                viewModel.loadSearchResult()
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.listResponseLiveData.observe(this) {
            if (it.isFirstPage) {
                // 加载首页
                val list = ArrayList<Any>(BarcodeResultVM.PAGE_SIZE * 2)
                list.addAll(it.totalList)
                viewBinding.page.addData(data = list) {
                    it.pageList.isNotEmpty()
                }
            } else {
                // 加载更多
                viewBinding.page.addData(data = it.pageList) {
                    it.pageList.isNotEmpty()
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        // 打开页面，加载数据
        viewBinding.page.showLoading(refresh = true)
    }


    private fun BindingAdapter.BindingViewHolder.bindStandardProduct() {
        val viewBinding = getBinding<CellBarcodeResultStandardProductBinding>()
        val stdProduct = getModel<FetchProductByGtin14Query.StdProduct>()

        viewBinding.root.layoutParams =
            (viewBinding.root.layoutParams as StaggeredGridLayoutManager.LayoutParams).apply {
                isFullSpan = true
            }

        ImageUtils.loadImage(
            context,
            stdProduct.mainImg,
            viewBinding.vProductImg,
        )
        viewBinding.vProductName.text = stdProduct.title
        viewBinding.vProductBrandTitle.visibleOrGone(
            stdProduct.brand.isNullOrEmpty().not()
        )
        viewBinding.vProductBrand.visibleOrGone(
            stdProduct.brand.isNullOrEmpty().not()
        ) {
            text = stdProduct.brand
        }
    }
}
